package com.memory.test.controller;


import com.memory.test.comment.api.CommonPage;
import com.memory.test.comment.api.CommonResult;
import com.memory.test.nosql.document.EsWords;
import com.memory.test.service.WordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/esWords")
@Api(tags = "EsProductController", description = "搜索单词管理")
public class EsWordController {
    @Autowired
    private WordService wordService;

    @ApiOperation(value = "导入所有数据库中单词到ES")
    @RequestMapping(value = "/importAll", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Integer> importAllList() {
        int count = wordService.importAll();
        return CommonResult.success(count);
    }

    @ApiOperation(value = "根据id删除单词")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Object> delete(@PathVariable Long id) {
        wordService.delete(id);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "根据id批量删除单词")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) {
        wordService.delete(ids);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "根据id创建单词")
    @RequestMapping(value = "/create/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<EsWords> create(@PathVariable Long id) {
        EsWords esProduct = wordService.create(id);
        if (esProduct != null) {
            return CommonResult.success(esProduct);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "简单搜索")
    @RequestMapping(value = "/search/simple", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<EsWords>> search(@RequestParam(required = false) String keyword,
                                                    @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                    @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        Page<EsWords> esProductPage = wordService.search(keyword, pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(esProductPage));
    }
}
